<template>
  <el-dialog class="pick-dialog" title="确认订单" :visible.sync="dialogVisible" @close="reset" :close-on-click-modal="false" width="1000px">
    <div class="form-box">
      <div class="card-box">
        <el-table :data="infoArr" border style="width: 100%">
          <el-table-column prop="id" label="商品编号" width="100">
          </el-table-column>
          <el-table-column prop="gameName" label="游戏名称" width="100">
          </el-table-column>
          <el-table-column prop="address" width="100" label="区服">
            <template slot-scope="scope">
              <span>{{ scope.row.systemName ? scope.row.systemName + '/' : '' }}</span>
              <span>{{ scope.row.carrierName ? scope.row.carrierName + '/' : '' }}</span>
              <span>{{ scope.row.groupName ? scope.row.groupName + '/' : '' }}</span>
              <span>{{ scope.row.serverName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="des" label="简介">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.des" placement="top-start">
                <div class="zdy-des">{{ scope.row.des }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="" width="100" label="售价">
            <template>
              <div>
                {{isKefu?info.price:info.price}}
              </div>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <el-form :model="ruleForm" ref="ruleForm" label-width="80px" :inline="true" :rules="rules" class=" new_form_box">

        <el-form-item label="销售人" prop="saleUserId">
          <el-select filterable clearable v-model="ruleForm.saleUserId" placeholder="请选择销售人" @change="buyerChange">
            <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="销售渠道" prop="saleChannel">
          <el-input v-show="false" v-model="ruleForm.saleChannel" placeholder="请输入" />
          <span class="phone-box flex">
            <span class="name" v-if="ruleForm.saleChannel">{{ ruleForm.saleChannel }}</span>
            <el-button type="text" @click="openSelectQudao(2)">
              点击选择
            </el-button>
            <el-button v-if="ruleForm.saleChannel" type="del" @click="delPhone('saleChannel')">
              清空
            </el-button>
          </span>
        </el-form-item>
        <el-form-item label="三方单号" prop="otherNo">
          <el-input v-model="ruleForm.otherNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="游戏账号" prop="accountNumber">
          <el-input v-model="ruleForm.accountNumber" placeholder="请输入游戏账号" />
        </el-form-item>
        <el-form-item label="成本" prop="supplyAmount">
          <el-input v-model="ruleForm.supplyAmount" placeholder="请输入成本" @change="computedBuyerActualAmount" />
        </el-form-item>
        <el-form-item label="包赔费" prop="guaranteeAmount">
          <el-input v-model="ruleForm.guaranteeAmount" placeholder="请输入包赔费" @change="computedBuyerActualAmount" />
        </el-form-item>
        <el-form-item label="优惠价:" prop="saleAmount">
          <el-input @change="computedBuyerActualAmount" v-model="ruleForm.saleAmount" type="text" maxlength="11" placeholder="请输入出售价"></el-input>
        </el-form-item>
        <el-form-item label="支付状态" prop="salePay">
          <el-select v-model="ruleForm.salePay" placeholder="请选择支付状态">
            <el-option label="未支付" :value="1" />
            <el-option label="已支付" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="换绑状态" prop="changePhoneState">
          <el-select v-model="ruleForm.changePhoneState" placeholder="请选择换绑状态">
            <el-option label="未换绑" :value="1" />
            <el-option label="已换绑" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="换绑手机号:" label-width="100px" prop="changeTel">
          <el-input v-model="ruleForm.changeTel" type="text" maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <div class="sfk" v-if="ruleForm.actualAmount">
          <span>实付款：</span>
          <span class="price">
            <span>¥</span><span class="txt">{{ ruleForm.actualAmount }}</span>
          </span>
        </div>
        <el-form-item label="" prop="" class="row">
          <div class="upload_img_box flex">
            <el-form-item label="换绑截图" prop="changePhoneImg">
              <uploadImageOne v-model="ruleForm.changePhoneImg" @change="uploadSucccess($event,'changePhoneImg')"></uploadImageOne>
            </el-form-item>
            <el-form-item label="订单截图" prop="orderImg">
              <uploadImageOne v-model="ruleForm.orderImg" @change="uploadSucccess($event,'orderImg')"></uploadImageOne>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="其他图片" class="row">
          <el-upload :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess" :limit="50" :on-remove="handleRemove" :headers="headers">
            <div class="uploadbg">
              <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png" alt="">
              <br />
              <span>上传图片</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注:" label-width="60px" class="row" prop="remark">
          <el-input type="textarea" v-model="ruleForm.remark" placeholder="请输入备注" show-word-limit :rows="3" maxlength="300"></el-input>
        </el-form-item>
        <div style="margin: 10px 0;">
          <formSubTitVue title="财务信息"></formSubTitVue>
        </div>
        <el-form-item label="收款方" prop="shoukuanfang">
          <el-input v-model="ruleForm.shoukuanfang" placeholder="请输入收款方" />
        </el-form-item>
        <el-form-item label="收款账号" prop="shoukuanzhanghao">
          <el-input v-model="ruleForm.shoukuanzhanghao" placeholder="请输入收款账号" />
        </el-form-item>
      </el-form>
      <!-- <div class="price-box">
        <p>
          <span class="tit">原价：</span>
          <span class="price">¥{{ isKefu?info.price:info.price }}</span>
        </p>
        <p>
          <span class="tit">优惠价：</span>
          <span class="price">¥{{ ruleForm.saleAmount }}</span>
        </p>
      </div> -->

      <div class="center">
        <el-button @click="close('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">确认订单</el-button>
      </div>
    </div>
    <!-- <el-dialog @close="close2" title="扫码支付" :visible.sync="payQrShow" append-to-body :close-on-click-modal="false" width="240px">
      <iframe :srcdoc="payForm" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" width="200"
        height="200" style="overflow: hidden">
      </iframe>
      <div style="margin-top: 10px;">我已完成支付，<span class="link" @click="checkOrder">点击刷新</span></div>
    </el-dialog> -->
    <!-- <payQrcode ref="payQrcode" @close="close2" @success="checkOrder"></payQrcode> -->
    <qudaoDialog ref="qudaoDialog" @change="getSelectQudao"></qudaoDialog>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import searchApi from "@/api/pickUp/search.js";
import orderApi from "@/api/pickUp/order";
import { getUserProfile, getUser } from "@/api/system/user";
import supplyConfigApi from "@/api/system/supplyConfig";

import qudaoDialog from "../../recycleManage/recycleOrders/qudaoDialog.vue";
export default {
  name: "pick",
  components: { qudaoDialog },
  data() {
    var priceRule = (rule, value, callback) => {
      if (value&&!this.priceReg.test(value)) {
        callback(new Error("请输入正确的金额"));
      } else {
        callback();
      }
    };
    return {
      allUsers: [], //销售渠道
      isKefu: false,
      dialogVisible: false,
      loading: false,
      isEdit: false,
      payQrShow: false,
      payForm: "", //支付二维码参数
      info: "",
      infoArr: [],
      kefuList: [], //客服列表
      userInfo: {}, //当前登录人信息
      supplyInfo: {}, //卖家信息
      supydiscount: 0, //提号折扣
      checkList: [],
      yuangongList: [],
      imgShowList: [],
      ruleForm: {
        guazhang: 2,
        gameId: "",
        qufuIds: "",
        qufu: "",
        accountNumber: "",
        accountPassword: "",
        changeTel: "",
        saleAmount: "",
        actualAmount: "",
        supplyAmount: "",
        guaranteeAmount: "",
        saleUserId: "",
        guaranteeTenantName: "",
        supplyChannel: "", //供货商
        saleChannel: "",
        sellerName: "",
        salePay: "",
        guaranteePayStatus: "",
        shoukuanfang: "",
        shoukuanzhanghao: "",
        remark: "",
        otherNo: "",
        changePhoneState: "",
        changePhoneImg: "",
        orderImg: "",
      },
      newImages: [],
      imgFileList: [],
      uploadImgUrl: "",
      rules: {
        changeTel: [
          // { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        saleUserId: [
          { required: true, message: "请选择销售人", trigger: "change" },
        ],
        saleChannel: [
          { required: true, message: "请选择销售渠道", trigger: "change" },
        ],
        saleAmount: [
          { required: true, message: "请输入出售价", trigger: "blur" },
          { validator: priceRule, trigger: "blur" },
        ],
        supplyAmount: [
          { validator: priceRule, trigger: "blur" },
        ],
        guaranteeAmount: [
          { validator: priceRule, trigger: "blur" },
        ],
        changePhoneState: [
          { required: true, message: "请选择换绑状态", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    open(info, flag) {
      //console.log("%c Line:209 🥓 info", "color:#b03734", info);
      this.loading = false;
      this.info = info;
      this.infoArr = [info];
      this.getCurrentInfo();
      this.isEdit = false;
      this.ruleForm.id = info.id;
      this.ruleForm.goodsId = info.id;
      this.ruleForm.platformAmount = info.price;
      this.ruleForm.saleAmount = info.price;
      this.ruleForm.supplyAmount = info.costPrice || "";
      this.ruleForm.gameId = info.gameId;
      this.ruleForm.gameName = info.gameName;
      this.ruleForm.accountNumber = info.accountNumber;
      this.ruleForm.qufu = `${info.systemName ? info.systemName + "/" : ""}${
        info.carrierName ? info.carrierName + "/" : ""
      }${info.groupName ? info.groupName + "/" : ""}${info.serverName}`;

      this.ruleForm.dataType = "buy";
      this.ruleForm.sourceScen = 4;
      this.computedBuyerActualAmount();
      this.dialogVisible = true;
      if (flag == "kefu") {
        this.isKefu = true;
        this.ruleForm.dataType = "all";
      } else {
        this.isKefu = false;
        // this.getKefuList()
      }
      this.getYuangongList();
      // this.getUserSupply(info.createId);
    },

    // 获取所有员工列表
    getYuangongList() {
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          this.yuangongList = res.rows;
        });
    },

    // // 获取供货商信息
    // getUserSupply(supplyId) {
    //   getUser(supplyId).then((res) => {
    //     this.supplyInfo = res.data;
    //   });
    // },
    // // 搜索销售渠道
    // getAllUserList(val) {
    //   supplyConfigApi.getAllUserList().then((res) => {
    //     this.allUsers = res.rows;
    //   });
    //   // if(val){
    //   //   let obj = {
    //   //     nickName:val
    //   //   }
    //   //   supplyConfigApi.getAllUserList(obj).then(res => {
    //   //     //console.log("%c Line:104 🍯 所有用户res", "color:#93c0a4", res);
    //   //     this.allUsers = res.rows
    //   //   })
    //   // }
    // },
    // // 销售渠道改变
    // saleChannelChange(e) {
    //   if (e) {
    //     this.allUsers.forEach((r) => {
    //       if (r.userId == e) {
    //         this.supydiscount = r.supydiscount;
    //         this.computedSfk();
    //       }
    //     });
    //   } else {
    //     this.ruleForm.saleChanelId = "";
    //     this.supydiscount = 0;
    //   }
    // },
    // // 计算实付金额
    // computedActualAmount(){
    //   let num = this.ruleForm.saleAmount * (!this.supydiscount||this.supydiscount=='0.0'||this.supydiscount==0?10:this.supydiscount) / 10
    //   this.ruleForm.actualAmount = num<0.01?0.01:num
    //   return false
    // },
    // 获取客服列表
    getKefuList() {
      searchApi.getKefuList().then((res) => {
        this.kefuList = res.data;
        // this.ruleForm.serviceUserId = res.data[0].id
        // this.ruleForm.serviceUserName = res.data[0].name
      });
    },
    // 选择客服
    kefuChange(val) {
      this.kefuList.forEach((t) => {
        if (t.id == val) {
          this.ruleForm.serviceUserName = t.name;
        }
      });
    },
    /**选择相关  start*/
    //  取消选中渠道
    delPhone(type) {
      if (type == "phone") {
        this.ruleForm.telid = "";
        this.ruleForm.isMyTel = "";
        this.ruleForm.changeTel = "";
      } else if (type == "guaranteeTenantName") {
        this.ruleForm.guaranteeTenantName = "";
      } else if (type == "saleChannel") {
        this.ruleForm.saleChannel = "";
      } else if (type == "supplyChannel") {
        this.ruleForm.supplyChannel = "";
      }

      this.$forceUpdate();
    },
    // 打开渠道哦选择
    openSelectQudao(type) {
      this.$refs.qudaoDialog.open(type);
    },
    // 渠道选择完成
    getSelectQudao(item) {
      if (item.type == 1) {
        // 包赔商
        this.ruleForm.guaranteeTenantName = item.name;
      } else if (item.type == 2) {
        // 平台渠道
        this.ruleForm.saleChannel = item.name;
      } else if (item.type == 3) {
        // 供货商
        this.ruleForm.supplyChannel = item.name;
      }
      this.$forceUpdate();
    },
    /**选择相关  end*/

    // 销售人 改变
    buyerChange(e) {
      if (e) {
        for (let i = 0; i < this.yuangongList.length; i++) {
          if (this.yuangongList[i].userId == e) {
            this.ruleForm.saleUserNickname = this.yuangongList[i].nickName;
          }
        }
      } else {
        this.ruleForm.saleUserNickname = "";
      }
    },

    // 获取当前登录人信息
    getCurrentInfo() {
      getUserProfile().then((res) => {
        this.userInfo = res.data;
      });
    },
    // // 计算实付金额
    // computedSfk() {
    //   let num = 0;
    //   if (this.isKefu) {
    //     num =
    //       (this.ruleForm.saleAmount *
    //         (!this.supydiscount ||
    //         this.supydiscount == "0.0" ||
    //         this.supydiscount == 0
    //           ? 10
    //           : this.supydiscount)) /
    //       10;
    //   } else {
    //     num = (this.info.price * (this.supydiscount || 10)) / 10;
    //   }
    //   this.ruleForm.actualAmount =
    //     num < 0.01 ? 0.01 : Math.round(num * 100) / 100;
    //   this.$forceUpdate();
    // },

    // 价格改变  计算利润
    computedBuyerActualAmount() {
      const guaranteeAmount = Number(this.ruleForm.guaranteeAmount || 0);
      if (this.ruleForm.saleAmount) {
        const total = Number(this.ruleForm.saleAmount) + guaranteeAmount;
        this.ruleForm.actualAmount = Math.round(total * 100) / 100;
      }
      if (this.ruleForm.actualAmount && this.ruleForm.supplyAmount) {
        const profits =
          Number(this.ruleForm.actualAmount) -
          Number(this.ruleForm.supplyAmount);
        this.ruleForm.profits = Math.round(profits * 100) / 100;
      }
      this.$forceUpdate();
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          // 拼接新上传的图片
          if (this.newImages && this.newImages.length) {
            let newArr = [];
            this.newImages.forEach((img) => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath,
              });
            });
            this.ruleForm.img = JSON.stringify(this.imgFileList.concat(newArr));
          } else {
            this.ruleForm.img = JSON.stringify(this.imgFileList);
          }

          // 处理收款信息
          let collection = {
            shoukuanfang: this.ruleForm.shoukuanfang,
            shoukuanzhanghao: this.ruleForm.shoukuanzhanghao,
          };
          this.ruleForm.collection = JSON.stringify(collection);

          orderApi
            .addOrder(this.ruleForm)
            .then((res) => {
              this.loading = false;
              if (res.code == 200) {
                // 下单成功
                // // 跳转订单详情页面
                this.$message.success("订单提交成功");
                this.$parent.getList();
                // 加时间戳
                const timestamp = new Date().getTime();
                this.$router.push({
                  path: "/tenantOrders/SaleOrderPage",
                  query: {
                    orderStatus: 4,
                    timestamp,
                  },
                });
                this.close();
              }
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          this.$alert("请将表单填写完整！");
          //console.log("error submit!!");
          return false;
        }
      });
    },

    // 单张图片上传成功
    uploadSucccess(e, key) {
      this.ruleForm[key] = e;
    },
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 详情图片删除
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传50张图片");
    },

    close(formName) {
      this.dialogVisible = false;
      this.$refs.ruleForm.resetFields();
    },
    // 重置
    reset() {
      this.$refs.ruleForm.resetFields();
    },
    // close2() {
    //   this.dialogVisible = false;
    //   if (this.isKefu) {
    //     this.$router.push({
    //       name: "SaleOrderKF",
    //       query: {
    //         orderStatus: "3",
    //       },
    //     });
    //   } else {
    //     this.$router.push({
    //       name: "BusinessOrderList",
    //       query: {
    //         from: "businessCenter",
    //         orderStatus: "3",
    //       },
    //     });
    //   }
    // },
  },
};
</script>
<style scoped lang="scss">
.tip {
  color: #ff0000;
  line-height: 22px;
}

.price-box {
  text-align: right;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
  padding-right: 20px;
}

.sfk {
  text-align: right;
  padding-right: 20px;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 10px;

  .txt {
    font-size: 26px;
    color: #ff0000;
    margin-left: 5px;
  }
}

::v-deep .upload_img_box .el-form-item {
  width: 240px;
}
.phone-box {
  align-items: center;
}
.phone-box .name {
  white-space: nowrap;
  width: 84px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
